<template>
  <div class="field-wrapper">
    <div class="field-inner">
      <!-- 如果是文件 -->
      <apple-button v-if="type === 'file'" block width="width" class="file-wrapper">
        <span v-html="fileText"></span>
        <input
          required
          v-autofocus="autofocus"
          ref="rawFile"
          type="file"
          :class="inputClass"
          :style="inputStyle"
          :value="modelValue"
          :name="name"
          :disabled="disabled"
          :placeholder="placeholder"
          @focus="$emit('focus', $event.target.value)"
          @blur="handleBlur($event)"
          @change="receiveChange"
          @input="handleInput($event)"
        />
      </apple-button>
      <!-- 不是文件 -->
      <template v-else>
        <input
          ref="rawFile"
          required
          v-autofocus="autofocus"
          :class="inputClass"
          :style="inputStyle"
          :type="password ? (passwordVisible ? 'text' : 'password') : type"
          :value="modelValue"
          :name="name"
          :disabled="disabled"
          :placeholder="placeholder"
          @focus="$emit('focus', $event.target.value)"
          @blur="handleBlur($event)"
          @change="$emit('change', $event)"
          @input="handleInput($event)"
        />
      </template>
      <span v-if="type !== 'file'" class="v-input-label">{{ label }}</span>
      <div v-if="line" class="line"></div>
    </div>
    <span v-if="rules.length > 0" class="v-error-msg">{{ errorMsg }}</span>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType, inject, ref } from "vue";
import { IRole } from "@/interface";
import { IMessage } from '@/interface/IUse';
import AppleButton from '@/components/apple/AppleButton.vue';
export default defineComponent({
  name: "v-input",
  components: {
    AppleButton
  },
  props: {
    label: {
      type: String,
      default: "",
    },
    modelValue: {
      type: [String, Number],
      default: "",
    },
    placeholder: {
      type: String,
      default: "请输入",
    },
    name: {
      type: String,
      default: null,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    password: {
      type: Boolean,
      default: false,
    },
    type: {
      type: String,
      default: "text",
    },
    line: {
      type: Boolean,
      default: false,
    },
    rules: {
      type: Object as PropType<Array<IRole>>,
      default: () => []
    },
    autofocus: {
      type: Boolean,
      default: false
    },
    width: {
      type: String,
      default: '100%'
    }
  },
  emits: ['receiveFile'],
  setup(props, ctx) {
    const color = inject('$color');
    const $message: IMessage = inject('message') as IMessage;
    const fileText = ref('选择文件');
    const receiveChange = (event: InputEvent) => {
      const elm = event.target as HTMLInputElement;
      const length = elm?.files?.length;
      fileText.value = `选择了: <span class="v-red">"${length}"</span>个文件`;
      const path = elm.value;
      $message({
        type: 'success',
        content: `本次共选择了: ${length} 个文件, 路径为${path || '空'}`
      })
      ctx.emit('receiveFile', elm.files);
    };
    return { color, receiveChange, fileText };
  },
  computed: {
    inputStyle() {
      const styles: any = {};
      if (this.line) {
        styles.borderColor = 'transparent';
        styles.borderBottom = '1px solid #dfdfdf';
        styles.borderRadius = '0px';
      }
      if (this.type === 'file') {
        styles.height = 'auto';
        styles.paddingTop = styles.paddingRight = styles.paddingLeft = '0px';
        styles.paddingBottom = '10px';
      }
      return styles;
    },
    inputClass() {
      const classes = ['v-field', 'base'];
      if (this.line) {
        classes.pop();
        classes.push('input-line');
      }
      if (this.type === 'file') {
        classes.push('hide');
      }
      return classes;
    },
  },
  data() {
    return {
      passwordVisible: false,
      errorMsg: "",
      rawFile: null
    };
  },
  methods: {
    // 失去焦点
    handleBlur(event: Event) {
      const value = (event.target as HTMLInputElement).value;
      this.$emit("blur", value);
      // 将失去焦点和没有触发机制的规则筛选出来
      if (!this.rules || this.rules.length < 1) return;
      const rules = this.rules.filter(
        (rule: IRole) => rule.trigger === "blur" || !rule.trigger
      );
      const result = rules.every((rule: IRole) => this.checkout(rule, value));
      if (result) {
        this.errorMsg = "";
      }
    },
    // 输入框变化
    handleInput(event: Event) {
      const value = (event.target as HTMLInputElement).value;
      this.$emit("update:modelValue", value);
      // 将输入框变化和没有触发机制的规则筛选出来
      if (!this.rules || this.rules.length < 1) return;
      const rules = this.rules.filter(
        (rule: IRole) => rule.trigger === "change" || !rule.trigger
      );
      const result = rules.every((rule: IRole) => this.checkout(rule, value));
      if (result) {
        this.errorMsg = "";
      }
    },
    checkout(rule: IRole, value: number | string) {
      // VInput
      if (rule.require) {
        if (value !== 0 && !value) {
          const key = rule.key ? rule.key : "";
          this.setErrorStatus(rule, `请输入${key}, 该值不能为空!`);
          return false;
        }
      }
      if (rule.type) {
        if (!isNaN(value as any) && rule.type !== "number") {
          this.setErrorStatus(rule, `请输入${rule.type}!`);
          return false;
        }
        if (isNaN(value as any) && rule.type !== "string") {
          this.setErrorStatus(rule, `请输入${rule.type}!`);
          return false;
        }
      }
      if (rule.length) {
        if (typeof value === "string" && value.length > rule.length) {
          this.setErrorStatus(rule, `超出规定最大长度 ${rule.length}!`);
          return false;
        }
      }
      if (rule.max) {
        if (typeof value === "number" && value > rule.max) {
          this.setErrorStatus(rule, `超出规定最大值 ${rule.max}!`);
          return false;
        }
      }
      if (rule.min) {
        if (typeof value === "number" && value < rule.min) {
          this.setErrorStatus(rule, `超出规定最小值 ${rule.min}!`);
          return false;
        }
      }
      if (rule.validator && typeof rule.validator === "function") {
        const result = rule.validator(rule, value);
        // 如果返回的是false
        if (!result) {
          this.setErrorStatus(rule);
          return false;
        }
      }
      return true;
    },
    setErrorStatus(rule: IRole, def?: string) {
      this.errorMsg = rule.message || def;
    },
  },
});
</script>

<style scoped lang="scss">
.hide {
  width: 100% !important;
  position: absolute !important;
  left: 0 !important;
  top: 0 !important;
  bottom: 0 !important;
  right: 0 !important;
  opacity: 0 !important;
  z-index: 3 !important;
}
.v-error-msg {
  color: red;
  font-size: 12px;
  padding-left: 10px;
}
.field-wrapper {
  width: v-bind(width);
}

.v-field {
  display: block;
  width: 100%;
  height: 34px;
  padding: 10px;
  padding-top: 30px;
  padding-bottom: 15px;
  font-size: 16px;
  background: none;
  outline: none;
  border: none;
  border-radius: 4px;
  background-clip: padding-box;
  border: 1px solid #dfdfdf;
  transition: border-color 0.25s ease-in-out, box-shadow 0.25s ease-in-out;
  /* color: #666; */
  color: v-bind(color);
}

.v-field:focus {
  border-style: none !important;
}

/* 聚焦或者是有值的时候 才会添加以下样式 */
/* valid伪类必须配合required或者pattern使用 */
.v-field:focus + .v-input-label,
.v-field:valid + .v-input-label {
  /*color: #1976d2;*/
  color: $primary-color;
  font-size: 10px;
  top: 25%;
}
.v-field::placeholder {
  color: transparent;
  font-size: 14px;
  transition: all 0.25s ease-in-out;
}
.v-field:focus.v-field::placeholder {
  color: #757575;
}

.field-inner {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  overflow: visible;
}

.v-input-label {
  position: absolute;
  top: 50%;
  left: 12px;
  transform: translateY(-50%);
  /* color: #666; */
  color: v-bind(color);
  transition: all 0.25s;
  font-size: 16px;
}

.base:focus {
  /*border-color: #80bdff;*/
  border-color: $primary-color;
  /*box-shadow: 0 0 0 4px rgb(0 125 250 / 60%);*/
  box-shadow: 0 0 0 4px rgb(237 108 75 / 60%);
  /* box-shadow: 0 0 0 5px rgba(0, 123, 255, 0.25); */
}

.line {
  width: 0%;
  height: 2px;
  /*background-color: #1976d2;*/
  background-color: $primary-color;
  transition: width 0.25s;
  margin: 0 auto;
}

.input-line:focus ~ .line {
  width: 100%;
}


</style>